# ========================================
# CocoKeyboard Icon Auto-Copy Script
# ========================================

$OutputEncoding = [System.Text.Encoding]::UTF8
[Console]::OutputEncoding = [System.Text.Encoding]::UTF8

Write-Host ""
Write-Host "========================================" -ForegroundColor Cyan
Write-Host "CocoKeyboard Icon Auto-Copy Tool" -ForegroundColor Cyan
Write-Host "========================================" -ForegroundColor Cyan
Write-Host ""

$projectRoot = $PSScriptRoot
$resDir = Join-Path $projectRoot "app\src\main\res"
$drawableDir = Join-Path $resDir "drawable"

# Icon names
$sourceIcon = "ic_launcher"
$targetIcons = @("ic_app_icon_debug", "ic_app_icon_beta", "ic_app_icon_stable")

# Mipmap directories
$mipmapDirs = @(
    "mipmap-mdpi",
    "mipmap-hdpi", 
    "mipmap-xhdpi",
    "mipmap-xxhdpi",
    "mipmap-xxxhdpi",
    "mipmap-anydpi-v26"
)

Write-Host "[Step 1/4] Checking generated icons..." -ForegroundColor Yellow
Write-Host ""

# Check if icons were generated
$iconFound = $false
$testPath = Join-Path $resDir "mipmap-hdpi\$sourceIcon.png"
$testPathWebp = Join-Path $resDir "mipmap-hdpi\$sourceIcon.webp"

if (Test-Path $testPath) {
    $iconFound = $true
    $iconExt = ".png"
    Write-Host "  Found PNG format icons" -ForegroundColor Green
} elseif (Test-Path $testPathWebp) {
    $iconFound = $true
    $iconExt = ".webp"
    Write-Host "  Found WEBP format icons" -ForegroundColor Green
}

if (-not $iconFound) {
    Write-Host ""
    Write-Host "[ERROR] Generated icon files not found!" -ForegroundColor Red
    Write-Host "Please generate icons in Android Studio first:" -ForegroundColor Red
    Write-Host "  1. Right-click app folder" -ForegroundColor Gray
    Write-Host "  2. New > Image Asset" -ForegroundColor Gray
    Write-Host "  3. Name: ic_launcher" -ForegroundColor Gray
    Write-Host "  4. Click Finish" -ForegroundColor Gray
    Write-Host ""
    Write-Host "Press any key to exit..." -ForegroundColor Gray
    $null = $Host.UI.RawUI.ReadKey('NoEcho,IncludeKeyDown')
    exit 1
}

Write-Host ""
Write-Host "[Step 2/4] Creating backup..." -ForegroundColor Yellow

# Create backup
$backupDir = Join-Path $projectRoot "backup-icons-$(Get-Date -Format 'yyyyMMdd-HHmmss')"
Write-Host "  Backup directory: $backupDir" -ForegroundColor Gray
New-Item -ItemType Directory -Path $backupDir -Force | Out-Null

Write-Host ""
Write-Host "[Step 3/4] Cleaning old PNG files..." -ForegroundColor Yellow

# Clean up old PNG files to avoid conflicts with WEBP
$targetIcons = @("ic_app_icon_debug", "ic_app_icon_beta", "ic_app_icon_stable")
$cleanedCount = 0

foreach ($mipmapDir in $mipmapDirs) {
    $dirPath = Join-Path $resDir $mipmapDir
    
    if (-not (Test-Path $dirPath)) {
        continue
    }
    
    foreach ($targetIcon in $targetIcons) {
        $pngFile = Join-Path $dirPath "$targetIcon.png"
        $pngFileRound = Join-Path $dirPath "${targetIcon}_round.png"
        
        if (Test-Path $pngFile) {
            # Backup before deleting
            $backupPath = Join-Path $backupDir "$mipmapDir"
            New-Item -ItemType Directory -Path $backupPath -Force | Out-Null
            Copy-Item $pngFile (Join-Path $backupPath "$targetIcon.png") -Force -ErrorAction SilentlyContinue
            
            Remove-Item $pngFile -Force
            $cleanedCount++
        }
        
        if (Test-Path $pngFileRound) {
            $backupPath = Join-Path $backupDir "$mipmapDir"
            New-Item -ItemType Directory -Path $backupPath -Force | Out-Null
            Copy-Item $pngFileRound (Join-Path $backupPath "${targetIcon}_round.png") -Force -ErrorAction SilentlyContinue
            
            Remove-Item $pngFileRound -Force
            $cleanedCount++
        }
    }
}

if ($cleanedCount -gt 0) {
    Write-Host "  Removed $cleanedCount old PNG files" -ForegroundColor Green
} else {
    Write-Host "  No old PNG files to clean" -ForegroundColor Gray
}

Write-Host ""
Write-Host "[Step 4/4] Copying icons to all versions..." -ForegroundColor Yellow
Write-Host ""

# Copy icons from each mipmap directory
$copiedCount = 0
foreach ($mipmapDir in $mipmapDirs) {
    $sourcePath = Join-Path $resDir $mipmapDir
    
    if (-not (Test-Path $sourcePath)) {
        continue
    }
    
    Write-Host "  Processing: $mipmapDir" -ForegroundColor Cyan
    
    # Determine file extension based on directory
    if ($mipmapDir -eq "mipmap-anydpi-v26") {
        $ext = ".xml"
    } else {
        $ext = $iconExt
    }
    
    # Check source files
    $sourceFile = Join-Path $sourcePath "$sourceIcon$ext"
    $sourceFileRound = Join-Path $sourcePath "${sourceIcon}_round$ext"
    
    if (Test-Path $sourceFile) {
        # Backup and copy to all target versions
        foreach ($targetIcon in $targetIcons) {
            $targetFile = Join-Path $sourcePath "$targetIcon$ext"
            $targetFileRound = Join-Path $sourcePath "${targetIcon}_round$ext"
            
            # Backup old files
            if (Test-Path $targetFile) {
                $backupPath = Join-Path $backupDir "$mipmapDir"
                New-Item -ItemType Directory -Path $backupPath -Force | Out-Null
                Copy-Item $targetFile (Join-Path $backupPath "$targetIcon$ext") -Force
            }
            
            # Copy new files
            Copy-Item $sourceFile $targetFile -Force
            Write-Host "    Created: $targetIcon$ext" -ForegroundColor Green
            $copiedCount++
            
            # Handle round version
            if (Test-Path $sourceFileRound) {
                if (Test-Path $targetFileRound) {
                    $backupPath = Join-Path $backupDir "$mipmapDir"
                    Copy-Item $targetFileRound (Join-Path $backupPath "${targetIcon}_round$ext") -Force
                }
                Copy-Item $sourceFileRound $targetFileRound -Force
                Write-Host "    Created: ${targetIcon}_round$ext" -ForegroundColor Green
                $copiedCount++
            }
        }
    }
}

Write-Host ""
Write-Host "  Processing: drawable directory..." -ForegroundColor Cyan

# Copy drawable foreground and monochrome files
$drawableFiles = @(
    "${sourceIcon}_foreground.xml",
    "${sourceIcon}_background.xml",
    "${sourceIcon}_monochrome.xml"
)

foreach ($file in $drawableFiles) {
    $sourceFile = Join-Path $drawableDir $file
    
    if (Test-Path $sourceFile) {
        foreach ($targetIcon in $targetIcons) {
            $suffix = $file -replace "^${sourceIcon}_", ""
            $targetFile = Join-Path $drawableDir "${targetIcon}_$suffix"
            
            # Backup
            if (Test-Path $targetFile) {
                $backupDrawable = Join-Path $backupDir "drawable"
                New-Item -ItemType Directory -Path $backupDrawable -Force | Out-Null
                Copy-Item $targetFile (Join-Path $backupDrawable "${targetIcon}_$suffix") -Force
            }
            
            # Copy and replace content references
            $content = Get-Content $sourceFile -Raw -Encoding UTF8
            $content = $content -replace $sourceIcon, $targetIcon
            Set-Content $targetFile $content -Encoding UTF8 -Force
            
            Write-Host "    Created: ${targetIcon}_$suffix" -ForegroundColor Green
            $copiedCount++
        }
    }
}

# Copy PlayStore icon
$playstoreSource = Join-Path $projectRoot "app\src\main\${sourceIcon}-playstore.png"
if (Test-Path $playstoreSource) {
    Write-Host ""
    Write-Host "  Processing: PlayStore icons..." -ForegroundColor Cyan
    foreach ($targetIcon in $targetIcons) {
        $targetPlaystore = Join-Path $projectRoot "app\src\main\${targetIcon}-playstore.png"
        Copy-Item $playstoreSource $targetPlaystore -Force
        Write-Host "    Created: ${targetIcon}-playstore.png" -ForegroundColor Green
        $copiedCount++
    }
}

Write-Host ""
Write-Host "========================================" -ForegroundColor Green
Write-Host "SUCCESS! Copied $copiedCount files" -ForegroundColor Green
Write-Host "========================================" -ForegroundColor Green
Write-Host ""
Write-Host "Backup location: $backupDir" -ForegroundColor Gray
Write-Host ""
Write-Host "Next steps:" -ForegroundColor Yellow
Write-Host "  1. Android Studio menu: Build > Clean Project" -ForegroundColor White
Write-Host "  2. Then: Build > Rebuild Project" -ForegroundColor White
Write-Host "  3. Run the app to see new icons!" -ForegroundColor White
Write-Host ""
Write-Host "Press any key to exit..." -ForegroundColor Gray
$null = $Host.UI.RawUI.ReadKey('NoEcho,IncludeKeyDown')
